#coding=utf-8
'''
Created on 2017-06-12

@author: sandy
'''

import sys,platform
sys.path.append("../")
from twisted.internet import reactor
import ServerConfig
import ClientFactory
from pycommon import Daemon,LogManager
import logging
from pycommon import RemoteManager
from pycommon import Utils
import ManagerWebSite

if 'twisted.internet.reactor' not in sys.modules: 
    if platform.system() == "Linux":
        from twisted.internet import epollreactor
        epollreactor.install()  
    else:
        from twisted.internet import iocpreactor
        iocpreactor.install()

def ServerStart(isdaemon):
    logging.info("############Start ManagerServer############")
    ClientFactory.instance.start(ServerConfig.instance.server_ip,ServerConfig.instance.server_port,ServerConfig.instance.max_client)
    ManagerWebSite.instance.start(ServerConfig.instance.web_ip,ServerConfig.instance.web_port)
    pass

def ServerStop():
    ManagerWebSite.instance.stop()
    ClientFactory.instance.stop()
    pass  

def daemonFunc(isdaemon):
    LogManager.instance.setupLog(RemoteManager.instance.loglevel,RemoteManager.instance.logfile,isdaemon)
    ServerConfig.instance.loadFromFile()
    ServerStart(isdaemon)
    reactor.run()
    ServerStop()

def run():
    sid, msip, msport, pidpath, logfile, loglevel, pathSelfConfig = Utils.loadDaemonConfig(ServerConfig.instance.rundir)
    RemoteManager.instance.init(sid,msip,msport,logfile, loglevel)
    Daemon.run(pidpath, daemonFunc)

if __name__ == "__main__":
    run()